<template>
  <view class="container">
    <!-- 图片轮播——带右下角数量显示 -->
    <view class="advertisement">
      <swiper
        :interval="swiperInterval"
        :autoplay="swiperAutoplay"
        :circular="true"
        indicator-active-color="#00D075"
        indicator-color="#EDEEF0"
        :indicator-dots="false"
      >
        <swiper-item
          v-for="(item, index) in goodsSkuDetail.sku_images"
          :key="index"
          @click="previewMedia(index)"
        >
          <image
            :src="$util.img(item, { size: 'big' })"
            mode="aspectFit"
            lazy-load
          ></image>
        </swiper-item>
      </swiper>
    </view>
    <view
      class="timestamp flex-between"
      :style="{
        backgroundImage: 'url(' + $util.img('image/sanqi/tuan_3.png') + ')',
      }"
    >
      <view>
        <view class="c-base text-bold">
          <image
            :src="$util.img('image/sanqi/tuan_2.png')"
            class="li"
            mode="aspectFit"
            lazy-load
          ></image>
          团购
        </view>
        <view class="font-26" style="color: #e7e8eb"
          >已拼成{{ goodsSkuDetail.order_num }}{{ goodsSkuDetail.unit }}</view
        >
      </view>
      <view class="countdown">
        <view class="txt">距结束仅剩</view>
        <view class="clockrun">
          <uni-count-down
            :day="goodsSkuDetail.timeMachine.d"
            :hour="goodsSkuDetail.timeMachine.h"
            :minute="goodsSkuDetail.timeMachine.i"
            :second="goodsSkuDetail.timeMachine.s"
            color="#fff"
            splitorColor="#232940"
            backgroundColor="#232940"
          />
        </view>
      </view>
    </view>

    <view class="goodsInfo fill-base m-b-20">
      <view class="flex-between">
        <view class="font-52 c-origin flex-y-baseline text-bold">
          <view class="c-origin font-52 tetx-bold"
            ><text class="font-24">¥</text
            >{{ goodsSkuDetail.pintuan_price }}</view
          >
          <text
            class="font-24 c-a4 m-l-20"
            style="text-decoration: line-through"
            >原价:¥{{ goodsSkuDetail.price }}</text
          >
        </view>
        <view class="font-24 c-89"
          >已拼:{{ goodsSkuDetail.order_num }} 库存:{{
            goodsSkuDetail.order_num
          }}</view
        >
      </view>
      <view class="font-32 name m-b-10">{{ goodsSkuDetail.goods_name }}</view>
    </view>

    <!-- <view class="fill-base goodsInfo m-b-20 flex-between">
      <text class="text-bold">选择规格</text>
      <u-icon name="arrow-right" color="#A4A9B7" size="18"></u-icon>
    </view> -->

    <view class="fill-base m-b-20 p-24" v-if="newList.length > 0">
      <view v-for="(item, index) in newList" :key="index">
        <view class="group flex-between" v-if="item.end_time > timestamp">
          <view class="flex-y-center">
            <image
              :src="$util.img(item.headimg)"
              mode="aspectFit"
              lazy-load
            ></image>
            <text class="m-l-12 m-r-12" v-if="item.nickname">{{
              item.nickname
            }}</text>
            <text class="c-fb" v-if="item.timeMachine"
              >差{{ item.pintuan_num - item.pintuan_count }}人成团</text
            >
          </view>
          <view class="flex-y-center">
            <view v-if="item.timeMachine">
              <uni-count-down
                :day="item.timeMachine.d"
                :hour="item.timeMachine.h"
                :minute="item.timeMachine.i"
                :second="item.timeMachine.s"
                color="#FF2C39"
                splitorColor="#FF2C39 !important"
                background-color="transparent"
                borderColor="transparent"
              />
            </view>
            <block v-if="item.timeMachine">
              <text
                class="join m-l-10"
                @click="
                  openPinTuan(
                    item.group_id,
                    item.pintuan_num - item.pintuan_count,
                    item.end_time - item.currentTime,
                    item.headimg,
                    item.head_id
                  )
                "
                >参与拼团</text
              >
            </block>
            <block v-else>
              <text class="join m-l-10" style="background: #999">已结束</text>
            </block>
          </view>
        </view>
      </view>
    </view>

    <view class="fill-base goodsInfo m-b-20">
      <view class="font-32 text-bold">购买须知</view>
      <view class="c-78">
        {{ goodsSkuDetail.introduction }}
      </view>
    </view>

    <view class="fill-base goodsInfo">
      <view class="font-32 text-bold">商品详情</view>
      <view class="goods-details" v-if="goodsSkuDetail.goods_content">
        <rich-text
          :nodes="goodsSkuDetail.goods_content"
          @click="showImg($event)"
          :data-nodes="goodsSkuDetail.goods_content"
        ></rich-text>
      </view>
    </view>

    <view class="opetions fixfooter" :class="{ 'bottom-safe-area': isIphoneX }">
      <button class="items" open-type="share">
        <image
          :src="$util.img('/image/share.png')"
          mode=""
          style="width: 38rpx; height: 38rpx"
        ></image>
        <text>分享</text>
      </button>
      <view class="items" @click="editCollection()">
        <image
          :src="$util.img('/image/collection2.png')"
          mode=""
          v-if="whetherCollection == 1"
        ></image>
        <image :src="$util.img('/image/collection.png')" mode="" v-else></image>
        <text>收藏</text>
      </view>
      <view class="flex">
        <view class="add-cart" @click="pintuan"
          >团购价:¥{{ goodsSkuDetail.show_price }}</view
        >
      </view>
    </view>

    <!-- 商品sku -->
    <goods-sku
      ref="goodsSku"
      goodsType="pintuan"
      :showGoodsSku="showGoodsSku"
      :goods-detail="goodsSkuDetail"
      @refresh="refreshGoodsSkuDetail"
      @close="closeGoodsSku"
      v-if="showGoodsSku"
    ></goods-sku>
  </view>
</template>

<script>
import uniCountDown from "@/components/uni-count-down/uni-count-down.vue";
import goodsSku from "@/components/goods-sku/goods-sku.vue";
import htmlParser from "@/common/js/html-parser";
export default {
  components: {
    goodsSku,
    uniCountDown,
  },
  data() {
    return {
      StatusBar: getApp().globalData.StatusBar,
      token: "",
      isIphoneX: false, //判断手机是否是iphoneX以上
      skuId: 0,
      groupId: 0,
      pintuan_id: 0,
      whetherCollection: 0,

      showGoodsSku: false,

      memberId: 0,

      // 商品详情
      goodsSkuDetail: {
        goods_id: 0,
        goods_service: [],
      },

      // 解决每个商品SKU图片数量不同时，无法切换到第一个，导致轮播图显示不出来
      swiperInterval: 1,
      swiperAutoplay: false,
      //拼团组数据
      timestamp: "",
      newList: [],
      pintuanList: [],
      currentPintuan: {
        headimg: "",
        timeMachine: {},
      },
    };
  },
  async onLoad(data) {
    this.isIphoneX = this.$util.uniappIsIPhoneX();
    this.pintuan_id = data.pintuan_id || 0;
    if (data.id) {
      this.pintuan_id = data.id;
    }
    this.groupId = data.group_id || 0;
    if (data.source_member) uni.setStorageSync("invite_id", data.source_member);
    // 小程序扫码进入
    if (data.scene) {
      var sceneParams = decodeURIComponent(data.scene);
      sceneParams = sceneParams.split("&");
      if (sceneParams.length) {
        sceneParams.forEach((item) => {
          if (item.indexOf("id") != -1) this.pintuan_id = item.split("-")[1];
          if (item.indexOf("group_id") != -1)
            this.group_id = item.split("-")[1];
          if (item.indexOf("m") != -1)
            uni.setStorageSync("invite_id", item.split("-")[1]);
        });
      }
    }
    await this.getGoodsSkuDetail();
    this.getPintuanGroupList();
  },
  onShow() {
    //登录后查询
    this.token = uni.getStorageSync("token");

    if (this.token != "") {
      this.getMemberId();
    }
  },
  methods: {
    closeGoodsSku() {
      this.showGoodsSku = false;
    },
    //打开拼团弹出框
    openPinTuan(groupId, pintuan_num, time, headimg, head_id) {
      if (this.memberId == head_id) {
        this.$util.showToast({
          title: "您不能参与自己的团",
        });
        return;
      }
      this.currentPintuan = {
        groupId: groupId,
        pintuan_num: pintuan_num,
        timeMachine: this.$util.countDown(time),
        headimg: headimg,
      };
      this.joinPintuan();
    },
    //参与拼团
    joinPintuan() {
      this.goodsSkuDetail.group_id = this.currentPintuan.groupId;
      this.goodsSkuDetail.show_price = this.goodsSkuDetail.pintuan_price;
      this.goodsSkuDetail.save_price =
        this.goodsSkuDetail.price - this.goodsSkuDetail.show_price > 0
          ? (
              this.goodsSkuDetail.price - this.goodsSkuDetail.show_price
            ).toFixed(2)
          : 0;
      this.$forceUpdate();
      this.pintuan(false);
    },
    // 获取拼团组列表
    getPintuanGroupList() {
      this.$api.sendRequest({
        url: "/pintuan/api/pintuangroup/lists",
        data: {
          goods_id: this.goodsSkuDetail.goods_id,
        },
        success: (res) => {
          let data = res.data;
          this.timestamp = res.timestamp;
          if (data != null && data.length) {
            this.pintuanList = data;
            for (let i = 0; i < this.pintuanList.length; i++) {
              if (this.pintuanList[i]["end_time"] > res.timestamp) {
                this.pintuanList[i].timeMachine = this.$util.countDown(
                  this.pintuanList[i]["end_time"] - res.timestamp
                );
                this.pintuanList[i].currentTime = res.timestamp;
              } else {
                this.pintuanList[i].timeMachine = null;
              }
            }
            this.newList = this.pintuanList.filter((item) => {
              return item.end_time > res.timestamp;
            });
            console.log("拼团列表", this.newList);
            this.$forceUpdate();
          }
        },
      });
    },
    // 发起拼团
    pintuan(isPromotion = true) {
      if (!uni.getStorageSync("token")) {
        this.$util.showToast({
          title: "请先登录",
        });
        return;
      }
      if (isPromotion) {
        this.resetPrice();
      }
      this.showGoodsSku = true;
	  this.$nextTick(() => {
		  this.$refs.goodsSku.limitNumber = this.goodsSkuDetail.buy_num;
	  })
    },
    // 重置价格
    resetPrice() {
      this.goodsSkuDetail.group_id = 0;
      this.goodsSkuDetail.show_price = this.goodsSkuDetail.promotion_price;
      this.goodsSkuDetail.save_price =
        this.goodsSkuDetail.price - this.goodsSkuDetail.show_price > 0
          ? (
              this.goodsSkuDetail.price - this.goodsSkuDetail.show_price
            ).toFixed(2)
          : 0;
      this.$forceUpdate();
    },
    // 获取拼团商品详情
    async getGoodsSkuDetail() {
      let res = await this.$api.sendRequest({
        url: "/pintuan/api/goods/detail",
        async: false,
        data: {
          pintuan_id: this.pintuan_id,
        },
      });
      let data = res.data;
      if (data.goods_sku_detail != null) {
        this.goodsSkuDetail = data.goods_sku_detail;

        this.skuId = this.goodsSkuDetail.sku_id;
        this.goodsSkuDetail.group_id = this.groupId;

        //拼团倒计时
        if (this.goodsSkuDetail.end_time - res.timestamp > 0) {
          this.goodsSkuDetail.timeMachine = this.$util.countDown(
            this.goodsSkuDetail.end_time - res.timestamp
          );
        } else {
          this.$util.showToast({
            title: "活动已结束",
          });
          setTimeout(() => {
            this.$util.redirectTo("/pages/index/index", {}, "redirectTo");
          }, 1000);
        }

        if (this.goodsSkuDetail.sku_images)
          this.goodsSkuDetail.sku_images =
            this.goodsSkuDetail.sku_images.split(",");
        else this.goodsSkuDetail.sku_images = [];

        // 多规格时合并主图
        if (
          this.goodsSkuDetail.goods_spec_format &&
          this.goodsSkuDetail.goods_image
        ) {
          this.goodsSkuDetail.goods_image =
            this.goodsSkuDetail.goods_image.split(",");
          this.goodsSkuDetail.sku_images =
            this.goodsSkuDetail.sku_images.concat(
              this.goodsSkuDetail.goods_image
            );
        }

        this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";

        this.goodsSkuDetail.show_price =
          this.goodsSkuDetail.group_id == 0
            ? this.goodsSkuDetail.promotion_price
            : this.goodsSkuDetail.pintuan_price;

        this.goodsSkuDetail.save_price =
          this.goodsSkuDetail.price - this.goodsSkuDetail.show_price > 0
            ? (
                this.goodsSkuDetail.price - this.goodsSkuDetail.show_price
              ).toFixed(2)
            : 0;

        // 当前商品SKU规格
        if (this.goodsSkuDetail.sku_spec_format)
          this.goodsSkuDetail.sku_spec_format = JSON.parse(
            this.goodsSkuDetail.sku_spec_format
          );

        // 商品属性
        if (this.goodsSkuDetail.goods_attr_format) {
          let goods_attr_format = JSON.parse(
            this.goodsSkuDetail.goods_attr_format
          );
          this.goodsSkuDetail.goods_attr_format = this.$util.unique(
            goods_attr_format,
            "attr_id"
          );
          for (
            var i = 0;
            i < this.goodsSkuDetail.goods_attr_format.length;
            i++
          ) {
            for (var j = 0; j < goods_attr_format.length; j++) {
              if (
                this.goodsSkuDetail.goods_attr_format[i].attr_id ==
                  goods_attr_format[j].attr_id &&
                this.goodsSkuDetail.goods_attr_format[i].attr_value_id !=
                  goods_attr_format[j].attr_value_id
              ) {
                this.goodsSkuDetail.goods_attr_format[i].attr_value_name +=
                  "、" + goods_attr_format[j].attr_value_name;
              }
            }
          }
        }

        // 商品SKU格式
        if (this.goodsSkuDetail.goods_spec_format)
          this.goodsSkuDetail.goods_spec_format = JSON.parse(
            this.goodsSkuDetail.goods_spec_format
          );

        uni.setNavigationBarTitle({
          title: this.goodsSkuDetail.goods_name,
        });

        // 商品详情
        if (this.goodsSkuDetail.goods_content)
          this.goodsSkuDetail.goods_content = htmlParser(
            this.goodsSkuDetail.goods_content
          );

        if (this.token != "") {
          this.getWhetherCollection();
        }
      } else {
        this.$util.redirectTo("/pages/index/index", {}, "reLaunch");
      }
    },
    //获取用户是否关注
    getWhetherCollection() {
      this.$api.sendRequest({
        url: "/api/goodscollect/iscollect",
        data: {
          goods_id: this.goodsSkuDetail.goods_id,
        },
        success: (res) => {
          this.whetherCollection = res.data;
        },
      });
    },
    editCollection() {
      if (this.token) {
        //未关注添加关注
        if (this.whetherCollection == 0) {
          this.$api.sendRequest({
            url: "/api/goodscollect/add",
            data: {
              sku_id: this.skuId,
              goods_id: this.goodsSkuDetail.goods_id,
              sku_name: this.goodsSkuDetail.sku_name,
              sku_price: this.goodsSkuDetail.show_price,
              sku_image: this.goodsSkuDetail.sku_image,
            },
            success: (res) => {
              var data = res.data;
              if (data > 0) {
                this.whetherCollection = 1;
              }
            },
          });
        } else {
          //已关注取消关注
          this.$api.sendRequest({
            url: "/api/goodscollect/delete",
            data: {
              goods_id: this.goodsSkuDetail.goods_id,
            },
            success: (res) => {
              var data = res.data;
              if (data > 0) {
                this.whetherCollection = 0;
              }
            },
          });
        }
      } else {
        this.$util.showToast({ title: '"请先登录"' });
      }
    },
    getMemberId() {
      this.$api.sendRequest({
        url: "/api/member/id",
        success: (res) => {
          if (res.code >= 0) {
            this.memberId = res.data;
          }
        },
      });
    },
    // 预览图片
    previewMedia(index) {
      var paths = [];
      for (let i = 0; i < this.goodsSkuDetail.sku_images.length; i++) {
        paths.push(
          this.$util.img(this.goodsSkuDetail.sku_images[i], {
            size: "big",
          })
        );
      }
      uni.previewImage({
        current: index,
        urls: paths,
      });
    },
    showImg(e) {
      //拿到图片的路径里面的内容放在我们数组中
      let contentimg = e.target.dataset.nodes;
      let arrImg = [];
      for (var i = 0; i < contentimg.length; i++) {
        var img = contentimg[i].children;
        for (var j = 0; j < img.length; j++) {
          if (img[j].attrs) {
            if (img[j].attrs.src) {
              arrImg.push(img[j].attrs.src);
            }
          }
        }
      }
      //最后一步就是把我们的所有图片放在预览的api中就可以了
      uni.previewImage({
        current: arrImg,
        urls: arrImg,
      });
    },
  },
  /**
   * 自定义分享内容
   * @param {Object} res
   */
  onShareAppMessage(res) {
    var path =
      "/otherpages/mall/tuanDetail?pintuan_id=" +
      this.pintuan_id +
      "&group_id=" +
      this.groupId;
    if (this.memberId) path += "&source_member=" + this.memberId;
    return {
      title: this.goodsSkuDetail.sku_name,
      imageUrl: this.$util.img(this.goodsSkuDetail.sku_image, {
        size: "big",
      }),
      path: path,
      success: (res) => {},
      fail: (res) => {},
    };
  },
  // #ifdef MP-WEIXIN
  // 分享到微信朋友圈
  onShareTimeline() {
    let query = "pintuan_id=" + this.pintuan_id + "&group_id=" + this.groupId;
    if (this.memberId) query += "&source_member=" + this.memberId;
    return {
      title: this.goodsSkuDetail.sku_name,
      query: query,
      imageUrl: this.$util.img(this.goodsSkuDetail.sku_image, {
        size: "big",
      }),
    };
  },
  // #endif
};
</script>

<style lang="scss" scoped>
.container {
  padding-bottom: 160rpx;
}
.fixHeader {
  position: fixed;
  top: 0;
  z-index: 9;
  width: 100%;
  box-sizing: border-box;
  .leftbtn {
    padding-left: 30rpx;
    // padding-top: 10rpx;
    margin-right: 30rpx;
    width: 60rpx;
    height: 60rpx;
  }
}
// 轮播图
.advertisement {
  position: relative;
  width: 750rpx;
  height: 750rpx;
  /deep/ swiper {
    height: 750rpx;
  }
  image {
    margin: 0 auto;
    width: 750rpx;
    height: 750rpx;
  }
}
.goodsInfo {
  padding: 30rpx 24rpx 20rpx;
  .name {
    line-height: 1.4;
  }
}

.opetions {
  padding: 10rpx 24rpx 10rpx 60rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  .items {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-right: 30rpx;
    image {
      width: 44rpx;
      height: 44rpx;
    }
    text {
      font-size: 24rpx;
      color: #606882;
    }
  }
  .add-cart {
    width: 335rpx;
    height: 86rpx;
    line-height: 86rpx;
    text-align: center;
    border-radius: 60rpx;
    background: #ff2c39;
    color: #fff;
    font-size: 26rpx;
  }
}

button {
  margin: 0;
  padding: 0;
  line-height: 1.8;
}

.line-l {
  display: inline-block;
  width: 79rpx;
  height: 2rpx;
  background: linear-gradient(90deg, #cccccc00 0%, #cccccc 100%);
  margin-right: 14rpx;
}
.line-r {
  display: inline-block;
  width: 79rpx;
  height: 2rpx;
  background: linear-gradient(90deg, #cccccc 0%, #cccccc00 100%);
  margin-left: 14rpx;
}

.cartBox {
  position: fixed;
  bottom: 20%;
  right: 24rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 108rpx;
  height: 108rpx;
  border-radius: 78rpx;
  background: #fff;
  z-index: 9;
  image {
    width: 88rpx;
    height: 88rpx;
  }
}

// 新增
.group {
  margin-bottom: 30rpx;
  image {
    width: 57rpx;
    height: 57rpx;

    border-radius: 60rpx;
    margin-right: 10rpx;
  }
  .join {
    padding: 4rpx 18rpx;
    display: inline-block;
    background: #fb4543;
    font-size: 24rpx;
    border-radius: 60rpx;
    color: #fff;
  }
}

.timestamp {
  position: relative;
  bottom: 0;
  width: 750rpx;
  height: 108rpx;
  overflow: hidden;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  box-sizing: border-box;
  padding: 18rpx 32rpx;
  .li {
    width: 36rpx;
    height: 38rpx;
    margin-right: 10rpx;
  }
  .countdown {
    position: absolute;
    right: 0;
    top: 0;
    width: 280rpx;
    text-align: center;
    height: 100%;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .txt {
      height: 32rpx;
      text-align: center;
      line-height: 32rpx;
      font-size: $font-size-tag;
      margin-top: 10rpx;
      color: #232940;
    }
    .clockrun {
      margin-top: 6rpx;
      height: 40rpx;
      line-height: 40rpx;
      text-align: center;
      font-size: $font-size-tag;
      color: #fff;
    }
  }
}
</style>
<style scoped>
.timestamp .countdown .clockrun >>> .uni-countdown__number {
  min-width: 32rpx;
  height: 32rpx;
  text-align: center;
  line-height: 32rpx;
  border-radius: 4px;
  display: inline-block;
  padding: 4rpx;
  margin: 0;
  border: none;
}

.timestamp .countdown .clockrun >>> .uni-countdown__splitor {
  width: 10rpx;
  height: 32rpx;
  line-height: 36rpx;
  text-align: center;
  display: inline-block;
}

.timestamp .countdown .clockrun >>> .uni-countdown__splitor.day {
  width: initial;
}

.spelling-block >>> .uni-countdown__splitor {
  padding: 0;
  font-size: 20rpx;
}

.sku-layer >>> .uni-popup__wrapper-box {
  overflow-y: initial !important;
}

.poster-layer >>> .uni-popup__wrapper-box {
  max-height: initial !important;
}

.spelling-block >>> .uni-countdown__number {
  padding: 0;
  margin: 0;
  font-size: 20rpx;
}

.pintuan-popup-layer >>> .uni-popup__wrapper-box {
  overflow-y: initial !important;
  border-radius: 10rpx;
}

.pintuan-popup-layer >>> .uni-countdown__number {
  padding: 0;
  margin: 0;
}
.group >>> .uni-countdown__number {
  padding: 0;
  margin: 0;
  font-size: 26rpx;
}
</style>
